/*	
 *	Generates Tag Cloud
 *	
 *	tagcloud.js
 *	An extension of jQuery which generates tag clouds
 *	
 *	Copyright (C) 2010  Pranav Prakash (pranav@myblive.com)
 *	
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *	
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *	
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *	
 *	
 *	http://blog.myblive.com/2010/10/easy-tagcloud-jquery-plugin.html
 *	
 *	Requires an array of JSON Objects with the following information
 *	name:	The name to display
 *	link:	The link to point to
 *	weight:	A count, which could describe the weights. The weight should be
 *			absolute, the plugin converts it into percentage automatically.
 *			And besides the weight is used to show the number of entries
 */
 
 
 (function($){
 
  $.fn.easyTagCloud = function(data, options) {
  	Array.max = function(array){
		return Math.max.apply( Math, array );
	};
	Array.min = function(array){
		return Math.min.apply( Math, array );
	};
    var settings = {
    	'algo'		:	'logarithmic',
    	'show_count'	:	true,
    	'tag_span_class':	'droplets',
    	'max_font' 	:	20,
    	'min_font' 	:	10,
    	'order'		:	null,
    };
    if(options) { 
    	$.extend( settings, options );
    }
    var total_weight = 0;
    var weights = [];
    $.each(data, function(index, droplet){
    	total_weight += droplet.weight;
    	weights.push(droplet.weight);
    });
    var min_weight = Array.min(weights);
    var max_weight = Array.max(weights);
    switch(settings.algo){
    	case 'linear': 
    		$.each(data, function(index, droplet){
    			var w = (droplet.weight - min_weight)/(max_weight - min_weight);
    			var f = settings.min_font + Math.round((settings.max_font - settings.min_font)* w);
    			droplet._font = f;
    		});
    	case 'logarithmic':
    		$.each(data, function(index, droplet){
    			var w = (Math.log(droplet.weight) - Math.log(min_weight))/(Math.log(max_weight) - Math.log(min_weight));
    			var f = settings.min_font + Math.round((settings.max_font - settings.min_font)* w);
    			droplet._font = f;
    		});
    }
    var x = [];
    $.each(data, function(index, droplet){
    	var xx = "<a href='"+ droplet.link +"' title='"+ droplet.weight +" entries'><span class='"+settings.tag_span_class+"' style='font-size:"+ droplet._font +"px;' >"+ droplet.name +"</span></a>";
    	x.push(xx);
    });
    $(this).html(x.join("<span class='spacer'>&nbsp;</span>"));
	return $(this);
  };
})( jQuery );
